package com.letere.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.letere.bean.Result;
import com.letere.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author letere
 * @create 2021-03-03 11:38
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        //工具类验证token是否正常
        if (JwtUtil.verify(token)) {
            return true;
        }
        //token异常不放行
        String result = new ObjectMapper().writeValueAsString(Result.failure("请求拦截！"));
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(result);
        return false;
    }
}
